package test.utility;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;

//import dm.java.a.e;

/*@d ps 2022-10-17
        执行sql功能
        */
public class SqlRun {
    @SuppressWarnings("serial")
    public static final HashMap<Integer, String> NetErrCodes = new HashMap<Integer, String>() {
        {
            put(6001, "网络通信异常");
            put(6060, "连接尚未建立或已经关闭");
            put(-6007, "连接异常");
        }
    };
    private Connection connection = null;
    private Statement stmt1 = null;
    private Statement stmt = null;
    private ResultSet rs = null;
    private boolean terminateFlag = false;
    private int errCode = 0;
    private String errMsg = "";
    private long execTime = -1l; //执行时间,单位毫秒

    public SqlRun() {
    }

    public SqlRun(String url, String uid, String pwd) {
        connect(url, uid, pwd);
    }

    public boolean getTerminateFlag() {
        return terminateFlag;
    }

    public int getErrCode() {
        return errCode;
    }

    public String getErrMsg() {
        return errMsg;
    }
        public long getExecTime () {
            return execTime;
        }
        public boolean connect (String url, String uid, String pwd){
            boolean flag = false;
            cleanErrmsg();
            try {
                connection = DriverManager.getConnection(url, uid, pwd);
                connection.setAutoCommit(true);
                flag = true;
            } catch (SQLException e) {
                dealWithExcep(e);
                System.err.println("[connect ERROR]. ErrorMsg:" + e.getMessage());
                flag = false;
            }
            return flag;
        }
        public void disconnect () {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    System.err.println("[disconnect ERROR], ErrorMsg:" + e.getMessage());
                }
            }
        }
        public Connection getConnect () {
            return connection;
        }
//执行不取出结果集的sql
        public boolean sqlWithoutRs (String sql){
            boolean flag = false;
            if (connection == null) {
//System. err. println("[exec ERROR]. ErrorMsg:connection is null");
                return flag;
            }
            cleanErrmsg();

        try {
            long startTime = System.currentTimeMillis();
            stmt1 = connection.createStatement();
            stmt1.execute(sql);
            long endTime = System.currentTimeMillis();
            execTime = endTime - startTime;
            flag = true;
        } catch (SQLException e) {
            flag = false;
            dealWithExcep(e);
        } finally {
            try {
                stmt1.close();
            } catch (SQLException e) {
// TODO Auto-generated catch block
//e. printStackTrace();
            }
        }
        return flag;
    }

    //执行需要取出结果集的sql
    public ResultSet sqlWithRsBegin(String sql) {
        if (connection == null) {
            return null;
        }
        if (stmt != null || rs != null){
            sqlWithRsFinish();
        }
        cleanErrmsg();
        try {
            stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            stmt.setEscapeProcessing(false);
            rs = stmt.executeQuery(sql);
        } catch (SQLException e) {
            dealWithExcep(e);
        }
        return rs;
    }


    public boolean sqlWithRsFinish() {
        boolean flag = false;
        try {
            if (rs != null) {
                rs.close();
                rs = null;
            }
            if (stmt != null) {
                stmt.close();
                stmt = null;

            }
            flag = true;
        } catch (SQLException e) {
        } catch (Exception e) {
//TODO
//有时候遇到不是sql异常，而是jdbc其它异常信息， 是否处理}

        }
        return flag;
    }
//执行并取出所有结果集
        public boolean executeSelect(String sql){
            boolean flag = false;
            if (connection == null) {
                return flag;
            }
            Statement stmt1 = null;
            cleanErrmsg();

            try {
                stmt1 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                stmt1.setEscapeProcessing(false);
                long startTime = System.currentTimeMillis();
                ResultSet rs1 = stmt1.executeQuery(sql);
                int i = 0;
                while (rs1.next()) {
                    i++;
                }
                rs1.close();
                long endTime = System.currentTimeMillis();
//System. out. println("--rows:" + i + "\n");
                execTime = endTime - startTime;
                flag = true;
            } catch (SQLException e) {
                flag = false;
                dealWithExcep(e);
            } finally {
                if (stmt1 != null) {
                    try {
                        stmt1.close();
                    } catch (SQLException e) {
// TODO Auto-generated catch block
//e. printStackTrace();
                    }
                }
            }
            return flag;
        }
        private void dealWithExcep (SQLException e){
            errMsg = e.getMessage();
            errCode = e.getErrorCode();
//System. err. println(String. format("[EXEC ERROR]%d,%s\n", errcode, e. getMessage()) );
            if (NetErrCodes.containsKey(errCode)) { //连接错误,程序退出
                terminateFlag = true;
            }
        }
        private void cleanErrmsg () {
            errCode = 0;
            errMsg = "";
            execTime = -1l;
        }

    }
